// @ts-ignore
import { debounce } from 'lodash';
import React, { useState, useEffect, useCallback } from 'react';
import {
  Button,
  Table,
  Space,
  Modal,
  Form,
  Input,
  message,
  Popconfirm,
  Spin,
  Typography,
  Card,
  Tooltip,
  Tag,
  Badge,
  Divider,
  Row,
  Col,
  Progress,
  Input as AntdInput
} from 'antd';
import {
  UserOutlined,
  EnvironmentOutlined,
  PhoneOutlined,
  IdcardOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  GlobalOutlined,
  ReloadOutlined,
  TeamOutlined,
  InfoCircleOutlined,
  AimOutlined
} from '@ant-design/icons';
import { Customer } from '../types';
import {
  getAllCustomers,
  addCustomer,
  updateCustomer,
  deleteCustomer,
  getCustomerCoordinates
} from '../services/customerService';

const { Title, Text } = Typography;
const { Search } = AntdInput;

const CustomerManagement: React.FC = () => {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [filteredCustomers, setFilteredCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [addressSearchValue, setAddressSearchValue] = useState('');
  const [form] = Form.useForm();
  const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);
  const [fetchingCoordinates, setFetchingCoordinates] = useState<{ [key: string]: boolean }>({});
  const [batchProcessing, setBatchProcessing] = useState(false);
  const [batchProgress, setBatchProgress] = useState(0);
  const [batchTotal, setBatchTotal] = useState(0);
  const [batchModalVisible, setBatchModalVisible] = useState(false);

  const loadCustomers = async () => {
    setLoading(true);
    try {
      const data = await getAllCustomers();
      setCustomers(data);
      setFilteredCustomers(data);
    } catch (error) {
      message.error('加载客户数据失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadCustomers();
  }, []);

  const showAddModal = () => {
    setEditingCustomer(null);
    form.resetFields();
    setModalVisible(true);
  };

  const showEditModal = (customer: Customer) => {
    setEditingCustomer(customer);
    form.setFieldsValue({
      name: customer.name,
      address: customer.address,
      phone: customer.phone,
      contact_person: customer.contact_person
    });
    setModalVisible(true);
  };

  const handleCancel = () => {
    setModalVisible(false);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);

      const customerData: Customer = {
        ...values
      };

      if (editingCustomer) {
        customerData.id = editingCustomer.id;
        customerData.location = editingCustomer.location;
        await updateCustomer(customerData);
        message.success('客户信息更新成功');
      } else {
        await addCustomer(customerData);
        message.success('客户添加成功');
      }

      setModalVisible(false);
      loadCustomers();
    } catch (error) {
      console.error('提交表单时出错:', error);
    } finally {
      setConfirmLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    setLoading(true);
    try {
      await deleteCustomer(id);
      message.success('客户删除成功');
      loadCustomers();
    } catch (error) {
      message.error('删除客户失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const fetchCoordinates = async (customerId: string) => {
    // 立即更新状态，显示加载图标
    setFetchingCoordinates(prev => ({ ...prev, [customerId]: true }));
    
    try {
      const customer = customers.find(c => c.id === customerId);
      if (!customer) {
        message.error('找不到指定的客户');
        return;
      }

      // 检查客户是否已有坐标
      if (customer.location) {
        Modal.info({
          title: '客户已有坐标',
          content: `客户 "${customer.name}" 已有坐标信息：${customer.location.longitude.toFixed(6)}, ${customer.location.latitude.toFixed(6)}`,
          okText: '确定'
        });
        return;
      }

      message.loading({ content: `正在获取"${customer.name}"的坐标...`, key: customerId });
      
      const updatedCustomer = await getCustomerCoordinates(customer);
      
      if (updatedCustomer && updatedCustomer.location) {
        message.success({ content: '获取坐标成功', key: customerId });
        // 使用函数式更新以避免闭包问题
        setCustomers(prev => prev.map(c => c.id === customerId ? updatedCustomer : c));
        setFilteredCustomers(prev => prev.map(c => c.id === customerId ? updatedCustomer : c));
      } else {
        message.error({ content: '无法获取坐标，请检查地址是否正确', key: customerId });
      }
    } catch (error) {
      console.error('获取坐标时出错:', error);
      message.error({ content: '获取坐标失败: ' + (error instanceof Error ? error.message : '未知错误'), key: customerId });
    } finally {
      setFetchingCoordinates(prev => ({ ...prev, [customerId]: false }));
    }
  };

  // 重构批量获取坐标功能，避免使用不兼容的特性
  const handleBatchGetCoordinates = useCallback(async () => {
    // 不使用message.loading等可能不兼容的功能
    const customersWithoutCoordinates = customers.filter(c => !c.location);

    // 检查是否所有客户都已有坐标
    if (customersWithoutCoordinates.length === 0) {
      // 使用alert替代可能有兼容性问题的Modal
      alert('所有客户已有坐标信息');
      return;
    }

    // 重置批量处理状态
    setBatchTotal(customersWithoutCoordinates.length);
    setBatchProgress(0);
    setBatchProcessing(true);
    setBatchModalVisible(true);

    let successCount = 0;
    let failCount = 0;
    const failedCustomers: string[] = [];

    // 使用普通的for循环而非async/await + forEach
    for (let i = 0; i < customersWithoutCoordinates.length; i++) {
      const customer = customersWithoutCoordinates[i];
      
      try {
        console.log(`处理客户 ${i+1}/${customersWithoutCoordinates.length}: ${customer.name}`);
        
        // 调用坐标获取API
        const updatedCustomer = await getCustomerCoordinates(customer);
        
        if (updatedCustomer && updatedCustomer.location) {
          successCount++;
          // 使用函数式更新避免闭包问题
          setCustomers(prevCustomers => 
            prevCustomers.map(c => c.id === customer.id ? updatedCustomer : c)
          );
          
          setFilteredCustomers(prevFiltered => 
            prevFiltered.map(c => c.id === customer.id ? updatedCustomer : c)
          );
        } else {
          failCount++;
          failedCustomers.push(customer.name);
        }
      } catch (error) {
        console.error(`获取客户 ${customer.name} 的坐标失败:`, error);
        failCount++;
        failedCustomers.push(customer.name);
      }

      // 更新进度
      setBatchProgress(i + 1);
      
      // 防止API限流，添加小延迟
      await new Promise(resolve => setTimeout(resolve, 300));
    }

    // 处理完成后的操作
    setBatchProcessing(false);
    
    // 显示处理结果
    setTimeout(() => {
      alert(`批量获取坐标完成: 成功${successCount}个, 失败${failCount}个`);
    }, 500);
  }, [customers]);  // 依赖项添加customers

  const handleBatchModalCancel = () => {
    if (!batchProcessing) {
      setBatchModalVisible(false);
    }
  };

  // 添加地址搜索功能
  const handleAddressSearch = useCallback(
    debounce((value: string) => {
      setAddressSearchValue(value);
      if (!value) {
        setFilteredCustomers(customers);
        return;
      }
      
      const filtered = customers.filter(customer => 
        customer.address.toLowerCase().includes(value.toLowerCase())
      );
      setFilteredCustomers(filtered);
    }, 300),
    [customers]
  );

  const columns = [
    {
      title: (
        <Space>
          <UserOutlined style={{ color: '#1890ff' }} />
          <span>客户名称</span>
        </Space>
      ),
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <Text strong style={{ fontSize: '14px' }}>
          <UserOutlined style={{ color: '#1890ff', marginRight: 8 }} />
          {text}
        </Text>
      ),
    },
    {
      title: (
        <Space>
          <EnvironmentOutlined style={{ color: '#52c41a' }} />
          <span>地址</span>
        </Space>
      ),
      dataIndex: 'address',
      key: 'address',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <Text type="secondary">
            <EnvironmentOutlined style={{ color: '#52c41a', marginRight: 8 }} />
            {text.length > 15 ? `${text.substring(0, 15)}...` : text}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: (
        <Space>
          <PhoneOutlined style={{ color: '#fa8c16' }} />
          <span>电话</span>
        </Space>
      ),
      dataIndex: 'phone',
      key: 'phone',
      render: (text: string) => (
        <Text>
          <PhoneOutlined style={{ color: '#fa8c16', marginRight: 8 }} />
          {text}
        </Text>
      ),
    },
    {
      title: (
        <Space>
          <IdcardOutlined style={{ color: '#722ed1' }} />
          <span>联系人</span>
        </Space>
      ),
      dataIndex: 'contact_person',
      key: 'contact_person',
      render: (text: string) => (
        <Text>
          <IdcardOutlined style={{ color: '#722ed1', marginRight: 8 }} />
          {text}
        </Text>
      ),
    },
    {
      title: (
        <Space>
          <GlobalOutlined style={{ color: '#eb2f96' }} />
          <span>位置坐标</span>
        </Space>
      ),
      key: 'location',
      render: (_: any, record: Customer) => (
        <Space>
          {record.location ? (
            <Tag color="green">
              {record.location.longitude.toFixed(6)}, {record.location.latitude.toFixed(6)}
            </Tag>
          ) : (
            <Tag color="red">未设置</Tag>
          )}
        </Space>
      ),
    },
    {
      title: (
        <Space>
          <InfoCircleOutlined style={{ color: '#1890ff' }} />
          <span>操作</span>
        </Space>
      ),
      key: 'action',
      render: (_: any, record: Customer) => (
        <Space size="small">
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
            style={{ background: '#1890ff' }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个客户吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
          <Button
            type="default"
            size="small"
            icon={<SearchOutlined />}
            onClick={() => fetchCoordinates(record.id)}
            loading={fetchingCoordinates[record.id]}
            style={{ background: '#f0f7ff', borderColor: '#91caff', color: '#1890ff' }}
          >
            获取坐标
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px', background: '#f0f2f5', minHeight: '100vh' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <Title level={2} style={{ margin: 0, color: '#1890ff' }}>
          <TeamOutlined style={{ marginRight: '12px' }} />
          客户管理
        </Title>
        
        <Space>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={showAddModal}
            style={{ 
              background: 'linear-gradient(90deg, #1890ff, #52c41a)',
              borderColor: '#1890ff',
              boxShadow: '0 2px 6px rgba(24,144,255,0.3)'
            }}
          >
            添加客户
          </Button>
          <Button
            type="primary"
            icon={<AimOutlined />}
            onClick={handleBatchGetCoordinates}
            style={{
              background: 'linear-gradient(90deg, #722ed1, #eb2f96)',
              borderColor: '#722ed1',
              boxShadow: '0 2px 6px rgba(114,46,209,0.3)'
            }}
          >
            一键获取坐标
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={loadCustomers}
            style={{ borderColor: '#d9d9d9' }}
          >
            刷新
          </Button>
        </Space>
      </div>

      <Card 
        style={{ 
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.08)'
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
          <Space>
            <Badge status="processing" />
            <Text strong>当前共有 {customers.length} 个客户</Text>
            <Text type="secondary">支持编辑、删除、获取坐标等操作</Text>
          </Space>
          
          <Search
            placeholder="输入地址关键词搜索"
            onSearch={value => handleAddressSearch(value)}
            onChange={e => handleAddressSearch(e.target.value)}
            style={{ width: 300 }}
            allowClear
          />
        </div>
        
        <Table
          columns={columns}
          dataSource={filteredCustomers}
          rowKey="id"
          loading={loading}
          pagination={{ 
            pageSize: 10,
            showTotal: (total) => `共 ${total} 条数据`,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50']
          }}
          bordered
          style={{ marginBottom: '16px' }}
          scroll={{ x: 'max-content' }}
          rowClassName={(record, index) => index % 2 === 0 ? 'even-row' : 'odd-row'}
        />
      </Card>

      <Modal
        title={
          <div>
            {editingCustomer ? (
              <Space>
                <EditOutlined style={{ color: '#1890ff' }} />
                <span>编辑客户</span>
              </Space>
            ) : (
              <Space>
                <PlusOutlined style={{ color: '#52c41a' }} />
                <span>添加客户</span>
              </Space>
            )}
          </div>
        }
        open={modalVisible}
        onCancel={handleCancel}
        confirmLoading={confirmLoading}
        onOk={handleSubmit}
        okText={editingCustomer ? '保存' : '添加'}
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            name: '',
            address: '',
            phone: '',
            contact_person: ''
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label={
                  <Space>
                    <UserOutlined style={{ color: '#1890ff' }} />
                    <span>客户名称</span>
                  </Space>
                }
                rules={[{ required: true, message: '请输入客户名称' }]}
              >
                <Input 
                  placeholder="请输入客户名称" 
                  prefix={<UserOutlined style={{ color: '#1890ff' }} />}
                  style={{ borderColor: '#91caff' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="contact_person"
                label={
                  <Space>
                    <IdcardOutlined style={{ color: '#722ed1' }} />
                    <span>联系人</span>
                  </Space>
                }
              >
                <Input 
                  placeholder="请输入联系人姓名" 
                  prefix={<IdcardOutlined style={{ color: '#722ed1' }} />}
                  style={{ borderColor: '#d3adf7' }}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="address"
            label={
              <Space>
                <EnvironmentOutlined style={{ color: '#52c41a' }} />
                <span>地址</span>
              </Space>
            }
            rules={[{ required: true, message: '请输入客户地址' }]}
          >
            <Input 
              placeholder="请输入客户地址，例如：广东省深圳市南山区科技园" 
              prefix={<EnvironmentOutlined style={{ color: '#52c41a' }} />}
              style={{ borderColor: '#b7eb8f' }}
            />
          </Form.Item>
          
          <Form.Item
            name="phone"
            label={
              <Space>
                <PhoneOutlined style={{ color: '#fa8c16' }} />
                <span>电话</span>
              </Space>
            }
          >
            <Input 
              placeholder="请输入联系电话" 
              prefix={<PhoneOutlined style={{ color: '#fa8c16' }} />}
              style={{ borderColor: '#ffd591' }}
            />
          </Form.Item>
          
          {editingCustomer && editingCustomer.location && (
            <div style={{ 
              background: '#f6ffed', 
              padding: '12px', 
              borderRadius: '6px',
              marginBottom: '16px',
              border: '1px solid #b7eb8f'
            }}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <GlobalOutlined style={{ color: '#52c41a', marginRight: '8px' }} />
                <Text strong>位置坐标</Text>
              </div>
              <div style={{ marginTop: '8px' }}>
                <Tag color="green">
                  经度: {editingCustomer.location.longitude.toFixed(6)}
                </Tag>
                <Tag color="green">
                  纬度: {editingCustomer.location.latitude.toFixed(6)}
                </Tag>
              </div>
            </div>
          )}
        </Form>
      </Modal>

      <Modal
        title={
          <div>
            <Space>
              <AimOutlined style={{ color: '#722ed1' }} />
              <span>批量获取客户坐标</span>
            </Space>
          </div>
        }
        open={batchModalVisible}
        onCancel={handleBatchModalCancel}
        footer={[
          <Button key="close" onClick={handleBatchModalCancel} disabled={batchProcessing}>
            关闭
          </Button>
        ]}
        width={500}
      >
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <div style={{ marginBottom: '20px' }}>
            {batchProcessing ? (
              <Text>正在批量获取客户坐标，请稍候...</Text>
            ) : (
              <Text>处理完成！</Text>
            )}
          </div>
          
          <Progress 
            percent={batchTotal > 0 ? Math.round((batchProgress / batchTotal) * 100) : 0}
            status={batchProcessing ? "active" : "success"}
            style={{ marginBottom: '20px' }}
          />
          
          <div style={{ marginTop: '10px' }}>
            <Text type="secondary">
              已处理: {batchProgress} / {batchTotal}
            </Text>
          </div>
        </div>
      </Modal>

      <style>
        {`
        .even-row {
          background-color: #ffffff;
        }
        .odd-row {
          background-color: #f9f9f9;
        }
        .ant-table-tbody > tr:hover > td {
          background-color: #e6f7ff !important;
        }
        `}
      </style>
    </div>
  );
};

export default CustomerManagement;